package com.kuqi.dao.impl;

import com.kuqi.dao.UserDao;
import com.kuqi.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author:kuqi
 * @createTime:2021/10/16 15:45
 * @description:
 */
public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<User> getUserList() {
        List<User> userList = jdbcTemplate.query("select * from sys_user",new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    @Override
    public Long save(User user) {

        //创建PrepareStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成有个Preparedment的组建
                PreparedStatement ps = connection.prepareStatement("insert into sys_user values (?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1,null);
                ps.setString(2,user.getUsername());
                ps.setString(3,user.getEmail());
                ps.setString(4,user.getPassword());
                ps.setString(5,user.getPhoneNum());
                return ps;
            }
        };

        //创建KeyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(creator,keyHolder);

        //获得生成的逐渐
        long userid = keyHolder.getKey().longValue();

        return userid;
    }

    @Override
    public void save_user_role(Long userid, long[] roleIds) {
        for (long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role value (?,?)",userid,roleId);
        }
    }

    @Override
    public void deleteUserRelationById(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
    }

    @Override
    public void delteUserById(Long userId) {
        jdbcTemplate.update("delete from sys_user where id=?",userId);
    }
}
